package com.hema.auction.http;

import android.content.Context;
import android.net.Uri;

import com.apkfuns.logutils.LogUtils;
import com.hema.auction.listener.RequestCallBack;
import com.hema.auction.utils.manager.SPManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * author by john
 * http请求工具（采用okhttp3）
 */
public class HttpEngine {

    private volatile static HttpEngine mInstance = null;
    private OkHttpClient client;
    private SPManager spManager;

    private HttpEngine(Context context) {
        client = new OkHttpClient();
        client.newBuilder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS);
        spManager = SPManager.getInstance(context);
    }

    public synchronized static HttpEngine getInstance(Context context) {
        if (null == mInstance) {
            synchronized (HttpEngine.class) {
                if (null == mInstance)
                    mInstance = new HttpEngine(context);
            }
        }
        return mInstance;
    }

    /**
     * 异步post请求
     *
     * @param url
     * @param params
     */
    public Call asyncPost(final HttpTag httpTag, String url, HashMap<String, String> params, final RequestCallBack callBack) {
        FormBody.Builder paramsBuilder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                paramsBuilder.add(key, params.get(key));
            }
        }
        paramsBuilder.build();
        LogUtils.d("------post = " + url + " --params = " + params.toString());
        Request.Builder request = new Request.Builder();
        request.url(url).post(paramsBuilder.build()).tag(httpTag).addHeader("Authorization", spManager.getToken()).addHeader("system", "android");
        Call call = client.newCall(request.build());
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(httpTag, call, e);
                callBack.onRequestFinish(httpTag);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                // 该回调是子线程，非主线程
                callBack.onResponse(httpTag, call, response);
                callBack.onRequestFinish(httpTag);
            }

        });
        return call;
    }

    /**
     * 异步get请求
     *
     * @param httpTag
     * @param url
     * @param params
     * @param callBack
     * @return
     */
    public Call asyncGet(final HttpTag httpTag, String url, HashMap<String, String> params, final RequestCallBack callBack) {
        if (params != null) {
            Uri uri = Uri.parse(url);
            Uri.Builder builder = uri.buildUpon();
            for (String key : params.keySet()) {
                builder.appendQueryParameter(key, params.get(key));
            }
            url = builder.build().toString();
        }

        LogUtils.d("------get = " + url);
        Request request = new Request.Builder().url(url).get().tag(httpTag).addHeader("Authorization", spManager.getToken()).
                addHeader("system", "android").build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(httpTag, call, e);
                callBack.onRequestFinish(httpTag);

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                if (response.isSuccessful()) {
                    callBack.onResponse(httpTag, call, response);
                    callBack.onRequestFinish(httpTag);
                } else {
                    callBack.onFailure(httpTag, call, new IOException());
                }
            }

        });
        return call;
    }

    public Call asyncGetNormal(final HttpTag httpTag, String url,final RequestCallBack callBack) {
        LogUtils.d("------get = " + url);
        Request request = new Request.Builder().url(url).get().tag(httpTag).build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(httpTag, call, e);
                callBack.onRequestFinish(httpTag);

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                if (response.isSuccessful()) {
                    callBack.onResponse(httpTag, call, response);
                    callBack.onRequestFinish(httpTag);
                } else {
                    callBack.onFailure(httpTag, call, new IOException());
                }
            }

        });
        return call;
    }

}
